﻿@model IEnumerable<Qu.SeniorProject.Model.ProjectSummary>

@section head {
    <style>
        em {
            font-weight: bold;
            padding-right: 1em;
            vertical-align: top;
            color: red;
        }

        a.linkStyle {
            padding-bottom: 10px;
        }

        tr.evenRaw {
            background-color: #FFFFEA;
        }

        tr.oddRaw {
            background-color: white;
        }
    </style>

    @*    <script type="text/javascript">
           function deleteConfirmation(response, status, data) {
               // display a status message with highlight
               $('#MarkProjectAsCompleteDiv').text(response.message);
               $('#MarkProjectAsCompleteDiv').effect("highlight", {}, 3000);

            }
        </script>*@

    <script language="javascript" type="text/javascript">
        $(document).ajaxStart(function () {
            $('.loadingDiv').show();
        });

        $(document).ajaxComplete(function () {
            $('.loadingDiv').hide();
        });

        $(document).ready(function () {
            $('.loadingDiv').hide();
            $('#message_bar').displayMessage({
                message: '@TempData["Message"]',
                color: 'white',
                speed: 'fast',
                autohide: true
            });

            $(".expanderContent").hide();
            $(".expanderSign").on('click', function () {
                $(this).text($(this).text() == '[+]' ? '[-]' : '[+]');
                $(this).parent().next("div").toggle();
            });

            $(".SourceUrlSubmissionLink").click(SourceUrlSubmission);
            $(".PreziUrlSubmissionLink").click(PreziUrlSubmission);

            $(".UploadHelpLink").click(function (e) {
                e.preventDefault();
                $('#UploadHelpDialog').dialog({
                    height: 600,
                    width: 800,
                    show: {
                        effect: "blind",
                        duration: 1000
                    },
                    hide: {
                        effect: "explode",
                        duration: 1000
                    }
                });
            });

            $("#PeriodIDdropdown").on("change keyup", function () {
                this.form.submit();
            })
        });


        function SourceUrlSubmission(event) {
            event.preventDefault();
            var form = $(this).closest('Form');
            var parentDiv = $(this).closest('div');
            var formValues = form.serializeArray();
            var formValuesJson = {};
            for (var i in formValues) {
                formValuesJson[formValues[i].name] = formValues[i].value;
            }
            if (!formValuesJson.SourceUrl.match("^http")) {
                alert("Invalid Url. The Document Link must be a valid http Url.");
                return;
            }

            if (formValuesJson.SourceUrl.toLowerCase().indexOf("dropbox") < 0) {
                alert("You must copy the document to be submitted to your Dropbox then Right-click the document and select 'Share Dropbox link' then paste the link in the textbox below.");
                return;
            }

            if (!formValuesJson.SourceUrl.match(formValuesJson.DocumentExtension + "$")) {
                alert("Invalid document extension. A document with the extension " + formValuesJson.DocumentExtension + " is expected");
                return;
            }

            $.ajax({
                url: '@Url.Action("DeliverableUrlSubmission", "document")',
                data: form.serialize(),
                dataType: "text json",
                method: "post",
                success: function (data) {
                    var msg = data.message;
                    msg = msg + '<br /><a href="' + data.sourceUrl + '">' + data.documentName + '</a>'
                    parentDiv.html(msg);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });
        }

        //function UrlExists(url) {
        //    jQuery.ajax({
        //        url: url,
        //        dataType: 'text',
        //        type: 'GET',
        //        complete: function (xhr) {
        //            if (xhr.status == 200)
        //                return true;
        //            else
        //                return false;
        //        }
        //    });
        //}

        function PreziUrlSubmission(event) {
            event.preventDefault();
            var form = $(this).closest('Form');
            var parentDiv = $(this).closest('div');
            var formValues = form.serializeArray();
            var formValuesJson = {};
            for (var i in formValues) {
                formValuesJson[formValues[i].name] = formValues[i].value;
            }
            if (!formValuesJson.PreziUrl.match("^http")) {
                alert("Invalid Url. The Presentation Link must be a valid http Url.");
                return;
            }

            //if (!UrlExists(formValuesJson.PreziUrl)) {
            //    alert("Invalid Url. Please make sure your Presentation Link is valid.");
            //    return;
            //}

            if (formValuesJson.PreziUrl.toLowerCase().indexOf("prezi") < 0) {
                alert("You must paste the public link for your Prezi Presentation that you have made available at prezi.com");
                return;
            }

            $.ajax({
                url: '@Url.Action("DeliverableUrlSubmission", "document")',
                data: form.serialize(),
                dataType: "text json",
                method: "post",
                success: function (data) {
                    var status = data.status;
                    var msg = data.message;
                    if (status === 'ok') {
                        msg = msg + '<br /><a href="' + data.sourceUrl + '">' + data.sourceUrl + '</a>'
                        parentDiv.html(msg);
                    }
                    else {
                        alert(msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Submission failed - " + errorThrown);
                    console.log(XMLHttpRequest.statusText);
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
        }

        // AJAX activity indicator bound to ajax start/stop document events
        //$(document).ajaxStart(function () {
        //    $('#ajaxBusy').show();
        //}).ajaxStop(function () {
        //    $('#ajaxBusy').hide();
        //});

        function showReleaseGradeForm(projectId) {
            console.log('showReleaseGradeForm ' + projectId);
            // Display the login dialog
            $("#dialog").dialog({
                minWidth: 500,
                modal: true,
                resizable: false,
                show: "scale",
                hide: "scale",
                position: "center",
                autoOpen: false,
                buttons: {
                    Ok: function () {
                        var addressFeedbackRating = $("#addressFeedbackRating").val();
                        var addressFeedbackComment = $("#addressFeedbackComment").val();

                        if (addressFeedbackRating == "") {
                            alert("Select a rating first");
                        }
                        else {
                            var controllerUrl = "@Url.Action("ReleaseGrades", "Home")";
                            var params = {
                                projectId: projectId,
                                ratingId: addressFeedbackRating,
                                comments: addressFeedbackComment
                            };

                            $('#ReleaseGradesDiv').hide();

                            $.ajax({
                                type: 'POST',
                                dataType: 'json',
                                url: controllerUrl,
                                data: params,
                                success:
                                     function (data) {
                                         if (data.success) {
                                             //alert("Data Loaded: " + data.message);
                                             $('#ReleaseGradesDiv').show();
                                             $('#ReleaseGradesDiv' + projectId).text(data.message);
                                             $('#ReleaseGradesDiv' + projectId).effect("highlight", {}, 3000);
                                         }
                                         else {
                                             alert(data.message);
                                         }
                                     },
                                error: function (data) {
                                    alert("Operation failed because : " + data + "\ns Please try again.");
                                    $('#ReleaseGradesDiv').show();
                                }
                            });

                            $(this).dialog("close");

                        }
                    },
                    Cancel: function () {
                        $(this).dialog("close");
                        $(this).dialog("destroy");
                    }
                }
            });

            $('#dialog').dialog('open');
        }


        function ValidateFileType(requiredExtension, fileInputControl, uploadButton, uploadForm) {

            //get filepath from fileupload control on the page
            var fileUpload = $(fileInputControl).val();

            //extracting part of the filename from dot
            var extension = fileUpload.substring(fileUpload.lastIndexOf('.'));

            //           //valid file type - static
            //           var ValidFileType = ".jpg , .png , .bmp";
            //           //or fetch it from config file for flexibility ,
            //           //we can save valid file type list in web.config also & fetch it during validation process
            //           var ValidFileTypeConfig = '<%=ConfigurationManager.AppSettings["ValidFileType"].ToString() %>';

            //check whether user has selected file or not
            if (fileUpload.length > 0) {

                //check file is of valid type or not
                if (requiredExtension.toLowerCase().indexOf(extension) < 0) {
                    alert("Invalid file type, you must select a " + requiredExtension + " file.");
                }
                else {
                    //alert("file type is valid...");
                    //$(uploadButton).attr('value', 'Please wait while the file is being uploaded...');
                    var btn = $(uploadButton);
                    var disBtn = $("<input type='button' value='Please wait while the file is being uploaded...'/>").attr("disabled", "disabled");

                    btn.hide().after(disBtn);
                    var form = $(uploadForm);
                    form.submit();

                    //                   $(uploadButton).unbind('click');
                    //                   $(uploadButton).attr("disabled", true);
                    return true;
                }
            }
            else {
                alert("Please select file for upload...");
            }
            return false;
        }
    </script>
}


@{
    ViewBag.Title = "CSE Senior Projects";
}

@if (ViewBag.StudentID == null)
{
    <!-- Login dialog -->
    <div id="dialog" title="Assess Addressing Examiners Feedback" style="display: none">
        <table cellpadding="4">
            <tr>
                <td><em>*</em>Rating:</td>
                <td>
                    @{
    var requiredField = new Dictionary<string, object>();
    requiredField.Add("class", "required");
    requiredField.Add("id", "addressFeedbackRating");

    SelectList ratingList = new SelectList(ViewBag.Ratings, "RatingID", "Description");
    @Html.DropDownList("addressFeedbackRating", ratingList, "", requiredField);
                    }
                </td>
            </tr>
            <tr>
                <td>Comments:</td>
                <td>
                    @{
                                                                                                  var commentsHtmlAttributes = new Dictionary<string, object>();
                                                                                                  commentsHtmlAttributes.Add("id", "addressFeedbackComment");
                                                                                                  commentsHtmlAttributes.Add("style", "width: 300px; height: 100px;");
                                                                                                @Html.TextArea("addressFeedbackComment", commentsHtmlAttributes);
                    }
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    Are you sure you would like to release the grades to students?
                    <br />
                    Please make sure that all the expected deliverables were submitted to you (note that often once the students access their grades they 'disappear').
                </td>
            </tr>
        </table>
    </div>
}

@if (ViewBag.StudentID == null)
{
    using (Html.BeginForm())
    {
        <b>Academic Year:</b> @Html.AjaxDropdown("PeriodID", controller: "ProjectPeriodAjaxDropdown")
        <br />
        <br />
    }
}

@if (!string.IsNullOrEmpty(ViewBag.Message))
{
    <h3>@ViewBag.Message</h3>

    if (ViewBag.StudentID == null)
    {
        if ((bool)ViewBag.CanAddProject)
        {
            @Html.ActionLink("Add Project", "AddProject", "Home");
        }
    }
    else
    {
        @Html.Partial("_MessageToStudentWithoutProject");
    }
    return;
}

@if (ViewBag.StudentID == null && (bool)ViewBag.CanAddProject)
{
    <p>
        @Html.ActionLink("Add Project", "AddProject", "Home")
    </p>
}

<div id='GradeDetails'></div>
<table>
    <tr>
        <th>
            ID
        </th>
        <th>
            Year
        </th>
        @if (ViewBag.StudentID == null)
        {
            <th>
                Your Role
            </th>
        }
        else
        {
            <th style="width : 0px"></th>
        }
        <th>
            Title
        </th>
        <th style="width : 320px">
            Students
        </th>
        <th style="width : 220px">
            Supervisor
        </th>
        <th style="width : 140px"></th>
    </tr>

    @DisplayProjectDetails()
</table>


@helper GetActionLinks(string role, int projectId, int periodId)
{
    var actionLinks = Qu.SeniorProject.Model.ProjectRepository.GetActionLinks(role, projectId, periodId);
    var routeValues = new System.Web.Routing.RouteValueDictionary();
    foreach (var actionLink in actionLinks)
    {

        if (actionLink.ActionName == "ReleaseGrades")
        {
            <div id="ajaxBusy" style="display: none">
                <img src="@Url.Content("~/Content/Images/ajaxloading.gif")" /><p id="ajaxBusyMsg">Please wait...</p>
            </div>
            <div id='@Html.Raw("ReleaseGradesDiv" + @projectId.ToString())'><a href="#" id="ReleaseGrades" onclick="showReleaseGradeForm('@projectId')">Release Grades to Students</a></div>
            @*                    <div id="MarkProjectAsCompleteDiv">
                @Ajax.ActionLink("Release Grades to Students", "MarkProjectAsComplete", new { projectID = item.ProjectID },
                            new AjaxOptions
                            {
                                UpdateTargetId = "message_bar",
                                HttpMethod = "POST",
                                Confirm = "Are you sure you would like to release the grades to students? Please make sure that all the expected deliverables was submitted to you (note that often once the students access their grades they 'disappear').",
                                OnSuccess = "deleteConfirmation"
                            })
                </div>*@
        }
        else
        {
            routeValues.Clear();

            foreach (var parameter in actionLink.Parameters.Split(','))
            {
                string[] parts = parameter.Split('=');
                routeValues.Add(parts[0], parts[1]);
            }

            //routeValues =
            @Html.ActionLink(actionLink.LinkLabel, actionLink.ActionName, actionLink.ControllerName, routeValues, null)
        }
        <br />
        <br />
    }
}


@helper DisplayProjectDetails()
{
    int index = 0;
    string cssClass;


    foreach (var item in Model)
    {
        index++;
        if (index % 2 == 0)
        {
            cssClass = "evenRaw";
        }
        else
        {
            cssClass = "oddRaw";
        }

        <tr class="@cssClass">
            <td>
                <b>@Html.ActionLink(item.ProjectID.ToString(), "ProjectDetails", new { id = item.ProjectID }) </b>
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ProjectYear)
            </td>
            @if (ViewBag.StudentID == null)
            {
                <td>
                    @Html.DisplayFor(modelItem => item.Role)
                </td>
            }
            else
            {
                <td></td>
            }
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.Raw(item.Students)
            </td>
            <td>
                @Html.Raw(item.Supervisors)
            </td>

            <td rowspan='3'>
                @GetActionLinks(item.Role, item.ProjectID, item.PeriodId)

            </td>
        </tr>

        <tr class="@cssClass">
            <td colspan='6'>
                <div class="expanderHead"><b>Abstract: </b><span class="expanderSign" style="cursor: pointer;">[+]</span></div>
                <div class="expanderContent">@Html.Raw(item.Abstract)</div>
            </td>
        </tr>
        if (item.PresentationDateTime != null && !string.IsNullOrEmpty(item.PresentationRoom)
                    && item.PresentationDateTime >= DateTime.Now.AddDays(-1)
                    && item.PresentationDateTime.Value.AddDays(-6) <= DateTime.Now)
        {
            <tr class="@cssClass">
                <td colspan='4'>
                    <b>Presentation Time:</b> @item.PresentationDateTime.Value.ToString("dd/MM/yyyy hh:mm tt") <b>at </b>@item.PresentationRoom
                    <br />

                    @if (item.PosterTime != null)
                    {
                        <b>Poster and Demo Time:</b> @item.PosterTime <b> at </b> @item.PosterVenue
                    }
                </td>

                @if (!string.IsNullOrEmpty(item.Examiners))
                {
                    <td colspan='2'>
                        <b>Examiners: </b>@Html.Raw(item.Examiners)
                    </td>
                }
                else
                    if (!string.IsNullOrEmpty(item.ProposalExaminer))
                    {
                        <td colspan='2'>
                            <b>Examiner: </b>@Html.Raw(item.ProposalExaminer)
                        </td>
                    }
            </tr>
        }

        <tr class="@cssClass">
            <td colspan='7'>
                @foreach (var doc in item.Documents)
                {
                    if (String.IsNullOrEmpty(doc.DocumentName))
                    {
                        <div class="linkStyle">
                            @doc.DocumentType <a href="@doc.SourceUrl" target="_blank">@doc.SourceUrl</a>
                        </div>
                    }
                    else
                    {
                        <div class="linkStyle">
                            @Html.ActionLink(linkText: doc.DocumentName, actionName: "Index", controllerName: "document", routeValues: new { id = string.Format("pd{0}", doc.DocumentId) }, htmlAttributes: null)
                        </div>
                    }
                }
                <br />
            </td>
        </tr>
        if (ViewBag.StudentID != null || (string)ViewBag.UserName == "erradi")
        {
            @GetDocumentUploadForms(item.ProjectID.ToString())

            @* Enter in the config table: revised interim report, FinalReport,  FinalPresentation, Poster, RevisedFinalReport *@
        }
        if (index < Model.Count())
        {
            <tr>
                <td colspan='7' style="border: 0px; padding: 0px;">
                    <hr size="4" color="#5C87B2">
                </td>
            </tr>
        }
    }
}


@helper GetDocumentUploadForms(string projectId)
{

    var deliverables = Qu.SeniorProject.Model.DocumentRepository.GetDueDeliverables(int.Parse(projectId));

    if (deliverables == null && deliverables.Count() == 0)
    {
        return;
    }

    foreach (var deliverable in deliverables)
    {
        string documentType = deliverable.DocumentType; //"InterimReport";
        string documentDescription = deliverable.DocumentDescription; //"Interim Report";
        string documentExtension = deliverable.DocumentExtension; //".docx";
        string dueDate = string.Format("Due by {0: hh:mm tt} on {1: dddd dd MMMM yyyy}", deliverable.DueDate, deliverable.DueDate);
        int academicYear = deliverable.AcademicYear;

        string fileInputName, uploadButtonName, uploadFormName;
        fileInputName = string.Format("{0}FileInput{1}", documentType, projectId);
        uploadButtonName = string.Format("{0}UploadButton{1}", documentType, projectId);
        uploadFormName = string.Format("{0}UploadForm{1}", documentType, projectId);

        <tr class="uploadRow">
            <td colspan='7'>
                <div><b>Upload @documentDescription</b> (must be @documentExtension file) <span style="color: Red;">- @dueDate </span></div>
                <br />
                <div style="color: Maroon;">Browse and select the file to be uploaded then click the Upload button</div>
                <br />

                <!--
                <div id="UploadHelpDialog" style="display:none" title="Help on how to upload your document using Dropbox">
                    <img src="~/Content/Upload-Using-Dropbox.gif" />
                </div>
                -->

                <div class="loadingDiv">
                    <img src="@Url.Content("~/Content/Images/ajaxloading.gif")" />Please wait...
                </div>
                @using (Html.BeginForm("Upload", "document", FormMethod.Post, new { enctype = "multipart/form-data", id = uploadFormName }))
                {
                    @Html.Hidden("ProjectId", projectId)
                    @Html.Hidden("DocumentType", documentType)
                    @Html.Hidden("DocumentExtension", documentExtension)
                    @Html.Hidden("AcademicYear", academicYear)

                    <text>File: </text><input type="file" name="file" id='@fileInputName' size="100" />
                    <input type="submit" value="Upload" id='@uploadButtonName'
                           onclick="return ValidateFileType('@documentExtension',  '#@fileInputName' , '#@uploadButtonName' , '#@uploadFormName');" />

                    <div style="padding-top: 10px">
                        <div class="expanderHead"><b>Alternative submission method in case of difficulties to upload your document:</b><span class="expanderSign" style="cursor: pointer;">[+]</span></div>
                        <div class="expanderContent">
                            <span style="color: Maroon;">
                                If you have difficulties uploading your submission
                                then could you please copy the document to be submitted to your Dropbox
                                <b>then Right-click the document and select 'Share Dropbox link' </b>
                                then paste the link in the textbox below and click Submit.
                                The system will attach your submission to the project then email you a confirmation message
                            </span>

                            <!--<a href="" class="UploadHelpLink">(click here to get more details).</a><br />-->
                            <br /><b>Dropbox link: </b> <input type="text" name="SourceUrl" style="width: 720px" />
                            <a href="" class="SourceUrlSubmissionLink">Submit</a>
                        </div>

                        @if (documentType.EndsWith("Presentation", StringComparison.InvariantCultureIgnoreCase))
                        {
                            <br /><b>Or paste the public link for your Prezi Presentation: </b>
                            <input type="text" name="PreziUrl" style="width: 720px" />
                            <a href="" class="PreziUrlSubmissionLink">Submit</a>
                        }

                        @*@Html.ActionLink(linkText: "Submit", actionName: "DownloadSubmission", controllerName: "Document", routeValues: null, htmlAttributes: new { @class = "uploadSubmission" })*@
                    </div>
                }
                <br />
            </td>
        </tr>
    }

}